﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class 场景管理器 : MonoBehaviour
{
    public static 场景管理器 m_当前场景管理器;

    public static List<string> m_全部场景列表 = new List<string>();

    public static List<string> m_激活场景列表 = new List<string>();

    public Dictionary<Scene, int> m_场景参数缓存 = new Dictionary<Scene, int>();

    AsyncOperation async;

    void Start()
    {
        if(m_当前场景管理器 == null)
        {
            m_当前场景管理器 = this;
        }
        else
        {
            Debug.LogError("场景中仅能有一个[场景管理器]");
        }

        SceneManager.LoadSceneAsync("logotest", LoadSceneMode.Additive);
        RenderSettings.fog = false;
        //SceneManager.LoadSceneAsync("logotest", LoadSceneMode.Additive);

        SceneManager.sceneLoaded += SceneManager_sceneLoaded;
        SceneManager.sceneUnloaded += SceneManager_sceneUnloaded;
    }

    private void SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1)
    {


        Debug.Log(arg0.GetHashCode());
    }

    private void SceneManager_sceneUnloaded(Scene arg0)
    {
        Debug.Log("SceneManager_sceneUnloaded Called!");
        if (m_场景参数缓存.ContainsKey(arg0))
        {
            if(m_场景参数缓存[arg0] == 1)
            {
                SceneManager.LoadScene(arg0.name, LoadSceneMode.Additive);
            }
        }

        Debug.Log(arg0.GetHashCode());
       // SceneManager.LoadScene(arg0.name, LoadSceneMode.Additive);
    }

    public void Update()
    {




    }

    public void 重新加载场景(Scene 场景)
    {
        m_场景参数缓存.Add(场景, 1); //表示该场景需要重新加载
        StartCoroutine(异步卸载场景(场景));
    }


    public void 卸载场景(Scene 场景)
    {
        StartCoroutine(异步卸载场景(场景));
    }

    public void 加载场景(string 场景名)
    {
        StartCoroutine(异步加载场景(场景名));
    }


    IEnumerator 异步卸载场景(Scene 场景)
    {
        async = SceneManager.UnloadSceneAsync(场景);    
         
        yield return async;
    }

    IEnumerator 异步加载场景(string 场景名)
    {
        async = SceneManager.LoadSceneAsync(场景名, LoadSceneMode.Additive);

        yield return async;
    }

}
